//
//  SLChargeViewController.m
//  SoccerLottery
//
//  Created by chuanshuangzhang chuan shuang on 15/12/24.
//  Copyright © 2015年 chuanshuangzhang. All rights reserved.
//

#import "SLChargeViewController.h"
#import "SLCionView.h"
#import <StoreKit/StoreKit.h>


#define kSandboxVerifyURL @"https://sandbox.itunes.apple.com/verifyReceipt" //开发阶段沙盒验证URL
#define kAppStoreVerifyURL @"https://buy.itunes.apple.com/verifyReceipt" //实际购买验证URL

@interface SLChargeViewController ()<SKPaymentTransactionObserver,SKProductsRequestDelegate>

@property (nonatomic,strong) UIScrollView *scrollView;

@property (nonatomic,strong) NSArray *dataSource;

@property (nonatomic,strong) SKProduct *product;

@property (nonatomic,strong) NSString *coinValue;

@end

@implementation SLChargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"购买金币" back:YES];
    _scrollView = [[UIScrollView alloc]init];
    _scrollView.frame = self.view.bounds;
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    _dataSource = @[@[@"gold_12",@"12"],@[@"gold_30",@"30"],@[@"gold_50",@"50"],@[@"gold_98",@"98"],@[@"gold_198",@"198"],@[@"gold_298",@"298"],@[@"gold_388",@"388"],@[@"gold_488",@"488"]];
    CGFloat width_distance = 30;
    CGFloat height_distance = 15;
    CGFloat width = (App_Frame_Width-3*width_distance)/2.0;
    CGFloat height = width * 0.7;
    
    for (NSInteger t = 0; t<_dataSource.count; ++t) {
        CGRect frame = CGRectMake(width_distance + t%2 * (width+width_distance) , height_distance+t/2 * (height + height_distance), width, height);
        SLCionView *coinView = [[SLCionView alloc]initWithFrame:frame];
        coinView.coinBtn.tag = t + 1;
        [coinView.coinBtn addTarget:self action:@selector(didSelectCoin:) forControlEvents:UIControlEventTouchUpInside];
        NSArray *arr = _dataSource[t];
        [coinView.coinBtn setBackgroundImage:[UIImage imageNamed:arr[0]] forState:UIControlStateNormal];
        coinView.valueLabel.text = [NSString stringWithFormat:@"%@元",arr[1]];
        [_scrollView addSubview:coinView];
    }

    CGFloat h = _dataSource.count/2.0 * (height + height_distance);
    if(h <= self.view.height){
        _scrollView.contentSize = CGSizeMake(App_Frame_Width, self.view.height+1);
    }else {
        _scrollView.contentSize = CGSizeMake(App_Frame_Width, h+height);
    }
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}


- (IBAction)didSelectCoin:(UIButton *)sender
{
    if(![VWebService isConnected]){
        return [SVProgressHUD showErrorWithStatus:@"无网络链接，请检查您的网络"];
    }
    NSInteger t = sender.tag - 1;
    
    NSString *productId = _dataSource[t][1];
    _coinValue = productId;
    productId = [NSString stringWithFormat:@"com.huashengmi.product_%@",productId];
    if([SKPaymentQueue canMakePayments]){
        [SVProgressHUD showWithStatus:@"正在处理"];
        NSArray *product = [[NSArray alloc] initWithObjects:productId,nil];
        NSSet *nsset = [NSSet setWithArray:product];
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
        request.delegate = self;
        [request start];
    }else{
        [SVProgressHUD showErrorWithStatus:@"您的手机没有打开程序内付费购买"];
    }
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    NSArray *products = response.products;
    if([products count] == 0){
        [SVProgressHUD showErrorWithStatus:@"获取金币失败，稍后再试"];
        return;
    }
    _product  = products[0];
    SKPayment *payment = [SKPayment paymentWithProduct:_product];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions//交易结果
{
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
            {//交易完成
                [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
                [self verifyPurchaseWithPaymentTransaction];
            }
                break;
            case SKPaymentTransactionStateFailed://交易失败
            {
                [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
                
                [SVProgressHUD showErrorWithStatus:@"充值失败"];
            }break;
            case SKPaymentTransactionStateRestored://已经购买过该商品
            case SKPaymentTransactionStatePurchasing:      //商品添加进列表
             
                break;
            default:
                break;
        }
    }
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [SVProgressHUD showErrorWithStatus:@"获取金币失败，稍后再试"];
}

- (void)requestDidFinish:(SKRequest *)request{
   
}
/**
 *  验证购买，避免越狱软件模拟苹果请求达到非法购买问题
 *
 */
-(void)verifyPurchaseWithPaymentTransaction{
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    //创建请求到苹果官方进行购买验证
    NSURL *url=[NSURL URLWithString:kAppStoreVerifyURL];
    NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody=bodyData;
    requestM.HTTPMethod=@"POST";
    //创建连接并发送同步请求
    NSError *error=nil;
    NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error];
    if (error) {
        [SVProgressHUD showSuccessWithStatus:@"充值失败"];
        return;
    }
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
    if([dic[@"status"] intValue]==0){
        [UserModel sharedInstance].coin = [NSString stringWithFormat:@"%ld",[[UserModel sharedInstance].coin integerValue]+[_coinValue integerValue]];
        if([UserModel sharedInstance].phone.length >= 11){
           [SLNewNetMgr setCoins:[UserModel sharedInstance].userId coins:_coinValue recommandId:@"" block:^(id result, BOOL status, NSError *error) {
               
           }];
        }
       [SVProgressHUD showSuccessWithStatus:@"充值成功"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"充值失败"];
    }
}

- (void)leftBarButtonItemAction:(id)sender
{
    [super leftBarButtonItemAction:sender];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
